/* eslint-disable default-case */
import { message } from 'antd';
import {
  socialCardList,
  socialCardSendInfor,
  cardAdd,
  cardDetail,
  cardUpdateDetail,
  cardUpdate,
  cardToDeal,
  cardToDealComplete,
  cardCancelToDeal,
  cardGrants,
  cardaddHdlRemark,
  cardHdlRemark,
  cardAddCheck,
  getMatList,
  getEmpNameList,
  getTemplate,
  checkCardInfor,
  abUploadFile,
  bUploadFile,
  ebUploadFile,
} from '@/services/socialservice';
import { getUploadProgress } from '@/services/careermange';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

const namespace = 'card';

let tagName;

export default {
  namespace,
  state: {
    batchQuery: {
      // // 批量上传数据
      areaId: null,
      contType: null,
      progressPercent: 0,
    },
    empNameList: [],
    empNameSelect: [],
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    sendData: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
    },
    // matData: {

    // },
    detail: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insCardHdl: {},
      matlist: {},
      remarklist: [],
    },
    updatedetail: {
      empSendInfoVo: {},
      empBaseInfoVo: {},
      insCardHdl: {},
      serMatPkgVo: { elementArr: [], matFileDictItem: [] },
    },
    detailHdl: [],
    fileId: '',
    fileName: '',
    messageData: {},
    tabList: [
      { itemCode: '1', itemName: '待办理' },
      { itemCode: '2', itemName: '办理中' },
      { itemCode: '3', itemName: '已办理' },
      { itemCode: '4', itemName: '已取消' },
    ],
    activeKey: '1',
    formFieldsValue: {},
    expandForm: false,
    resultInfo: {
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
  },

  effects: {
    getUploadProgress: [
      function*({ payload, callback }, { call, put }) {
        const response = yield call(getUploadProgress, payload);
        if (response.success) {
          yield put({
            type: 'updateQuery',
            payload: { progressPercent: response.data.successProp },
          });
        }
        if (callback && typeof callback === 'function') {
          callback(response);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(socialCardList, payload); // 请求
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList', // 处理后台返回数据
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },

    // 获取派单信息
    *fetchSendInfor({ payload }, { call, put }) {
      const response = yield call(socialCardSendInfor, payload); // 请求
      if (response.success) {
        yield put({
          type: 'sendList', // 处理后台返回数据
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 添加数据
    addList: [
      function*({ payload, callback }, { call }) {
        const response = yield call(cardAdd, payload);
        if (callback) callback(response);
      },
      { type: 'throttle', ms: 10000 },
    ],
    *fetchDetail({ payload }, { call, put }) {
      const response = yield call(cardDetail, payload);
      if (response.success) {
        yield put({
          type: 'getDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *fetchUpdateDetail({ payload }, { call, put }) {
      const response = yield call(cardUpdateDetail, payload);

      if (response.success) {
        yield put({
          type: 'getUpdateDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    updateList: [
      function*({ payload, callback }, { call }) {
        const response = yield call(cardUpdate, payload);
        if (response.success) {
          callback(response);
        } else {
          message.warning(response.message || '服务端错误');
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 开始办理
    *updateToDeal({ payload, callback }, { call }) {
      const response = yield call(cardToDeal, payload);
      if (response.success) {
        const isDisabled = response.data.some(item => item.success === false);
        if (!isDisabled) {
          callback(!isDisabled);
        } else {
          message.warning(response.data[0].message);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *updateToDealComplete({ payload, callback }, { call }) {
      const response = yield call(cardToDealComplete, payload);
      if (response.success) {
        const isDisabled = response.data.some(item => item.success === false);
        if (!isDisabled) {
          callback(!isDisabled);
        } else {
          message.warning(response.data[0].message);
        }
      } else {
        message.warning(response.message);
      }
    },
    *cancelToDeal({ payload, callback }, { call }) {
      const response = yield call(cardCancelToDeal, payload);
      if (response.success) {
        const isDisabled = response.data.some(item => item.success === false);
        if (!isDisabled) {
          callback(!isDisabled);
        } else {
          message.warning(response.data[0].message);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *updateGrants({ payload, callback }, { call }) {
      const response = yield call(cardGrants, payload);
      if (response.success) {
        const isDisabled = response.data.some(item => item.success === false);
        if (!isDisabled) {
          callback(!isDisabled);
        } else {
          message.warning(response.data[0].message);
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *addHdlRemark({ payload, callback }, { call }) {
      const response = yield call(cardaddHdlRemark, payload);
      if (callback) callback(response);
    },
    // 服务办理--办理备注
    *detailHdlRemark({ payload }, { call, put }) {
      const response = yield call(cardHdlRemark, payload);
      if (response.success) {
        yield put({
          type: 'getHdlRemark',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *addHdlRemarkDel({ payload, callback }, { call, put }) {
      const response = yield call(cardaddHdlRemark, payload);
      if (response.success) {
        callback(response);
        const resAgin = yield call(cardHdlRemark, { busiId: payload.busiId });
        if (resAgin.success) {
          yield put({
            type: 'updateData',
            payload: resAgin.data,
          });
        } else {
          message.warning(response.message || '服务端错误');
        }
      }
    },
    *addCheckList({ payload, callback }, { call }) {
      const response = yield call(cardAddCheck, payload);
      if (response.success) {
        callback(response);
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *fetchMatList({ payload }, { call, put }) {
      const response = yield call(getMatList, payload);
      if (response.success) {
        yield put({
          type: 'getMatList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 获取模糊查询员工姓名列表
    *fetchEmpNameList({ payload }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'getEmpNameList',
            payload: Array.isArray(response.data) ? response.data : [],
          });
        }
        if (!response.data.length) {
          message.warning('当前所输的不存在，请检查 ');
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *fetchEmpNoList({ payload, callback }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        if (response.data.length) {
          yield put({
            type: 'getEmpNoList',
            payload: Array.isArray(response.data) ? response.data : [],
          });
          callback(false);
        } else {
          message.warning('当前所输的证件号不存在，请检查 ');
          callback(true);
        }
      } else {
        callback(true);
        message.warning(response.message);
      }
    },
    *fetchTemplate({ payload }, { call, put }) {
      const response = yield call(getTemplate, payload);
      if (response.success) {
        yield put({
          type: 'getTemplate',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },
    *checkCard({ payload, callback }, { call, put }) {
      const response = yield call(checkCardInfor, payload);
      if (response.rspCode === '101') {
        callback(true);
        yield put({
          type: 'messageData',
          payload: response.message,
        });
      } else {
        callback(false);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress: [
      function*({ payload }, { call, put }) {
        const { tag, formData } = payload;
        let api;
        if (tag === 'ab') {
          api = abUploadFile;
        } else if (tag === 'eb') {
          api = ebUploadFile;
        } else {
          api = bUploadFile;
        }
        tagName = tag;
        const response = yield call(api, formData);
        if (response.success) {
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
          } else {
            yield put({
              type: 'updateBatchTask',
              payload: {
                payloadData: response.data,
                tag,
              },
            });
          }
        } else {
          // 上传失败
          message.warning(`${response.message || '上传失败'}`);
        }
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.card);
      let { showProgress, resultInfo, currentStep } = state;
      const { batchQuery } = state;
      const { payloadData, tag } = payload;
      showProgress = true;
      if (payloadData.successProp >= 100) {
        if (tag === 'ab') {
          resultInfo.errorParams = {
            batNo: payloadData.batchId,
          };
        } else if (tag === 'eb') {
          resultInfo.errorParams = {
            batNo: payloadData.batchId,
          };
        } else {
          resultInfo.errorParams = {
            batchId: payloadData.batchId,
            sendType: batchQuery.sendType,
            isSerSetFlag: batchQuery.isSerSetFlag,
          };
        }
        resultInfo = { ...resultInfo, ...payloadData };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payloadData.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payloadData.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新数据
    updateData(state, { payload }) {
      const remarklist = payload;
      return {
        ...state,
        detail: { ...state.detail, remarklist },
      };
    },
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    sendList(state, { payload }) {
      return {
        ...state,
        sendData: payload,
      };
    },
    // 获取详情
    getDetail(state, { payload }) {
      return {
        ...state,
        detail: payload,
      };
    },
    messageData(state, { payload }) {
      return {
        ...state,
        messageData: payload,
      };
    },
    getUpdateDetail(state, { payload }) {
      const elementArr = [];
      const maGpages = payload.serMatPkgVo.maGpages ? payload.serMatPkgVo.maGpages : [];
      if (maGpages.length) {
        maGpages.forEach(item => {
          if (item.maGpDetails.length) {
            item.maGpDetails.forEach(d => {
              const obj = {};
              if (d.children) {
                obj.children = d.children;
                obj.children.map(c => {
                  const newC = c;
                  if (Number(c.inpType) === 11) {
                    newC.areaValue = c.inpVal ? c.inpVal.split(',') : undefined;
                    newC.name = d.inpValName;
                  }
                  return true;
                });
              }
              if (Number(d.inpType) === 9) {
                const fileArr = d.inpVal ? d.inpVal.split(',') : [];
                const fileList = [];
                Object.keys(fileArr).forEach(key => {
                  const tempObj = {
                    uid: fileArr[key].split('|')[0],
                    name: fileArr[key].split('|')[1],
                    status: 'done',
                  };
                  fileList.push(tempObj);
                });
                obj.fileList = fileList;
              }
              obj.reqFlag = d.reqFlag; // 是否必填
              obj.matName = d.matName;
              obj.matId = d.matId;
              obj.inpType = d.inpType;
              obj.pageDetailId = d.pageDetailId;
              obj.dictItems = d.nmDictItem;
              if (d.inpVal) {
                obj.inpVal = d.inpVal;
              } else {
                obj.inpVal = d.dftVal;
              }
              if (Number(d.inpType) === 9) {
                const fileArr = d.inpVal ? d.inpVal.split(',') : [];
                const fileList = [];
                Object.keys(fileArr).forEach(key => {
                  const tempObj = {
                    uid: fileArr[key].split('|')[0],
                    name: fileArr[key].split('|')[1],
                  };
                  fileList.push(tempObj);
                });
                obj.fileList = fileList;
              }
              elementArr.push(obj);
            });
          }
        });
      }
      const { matFileDictItem } = payload.serMatPkgVo;
      const { empBaseInfoVo } = payload;
      const { empSendInfoVo } = payload;
      const { insCardHdl } = payload;
      Object.keys(insCardHdl).forEach(key => {
        if (key === 'copyFile') {
          insCardHdl[key] = insCardHdl[key].split(',');
        } else if (key === 'masterFile') {
          insCardHdl[key] = insCardHdl[key].split(',');
        }
      });
      elementArr.forEach((element, i) => {
        if (element.children && element.children.length) {
          element.children.forEach(item => {
            if (String(item.judgeLogicCode) === String(element.dftVal)) {
              elementArr.splice(i + 1, 0, item);
            }
          });
        }
      });
      return {
        ...state,
        coltFlag: payload.serMatPkgVo.coltFlag,
        updatedetail: { elementArr, matFileDictItem, empBaseInfoVo, empSendInfoVo, insCardHdl },
      };
    },

    getHdlRemark(state, { payload }) {
      return {
        ...state,
        detailHdl: Array.isArray(payload) ? payload : [],
      };
    },
    getMatList(state, { payload }) {
      const elementArr = [];
      const maGpages = payload.maGpages ? payload.maGpages : [];
      if (maGpages.length) {
        maGpages.forEach(item => {
          if (item.maGpDetails.length) {
            item.maGpDetails.forEach(d => {
              const obj = {};
              if (d.children) {
                obj.children = d.children;
              }
              obj.dftVal = d.dftVal; // 默认值
              obj.reqFlag = d.reqFlag; // 是否必填
              obj.matName = d.matName;
              obj.matId = d.matId;
              obj.inpType = d.inpType;
              obj.pageDetailId = d.pageDetailId;
              obj.dictItems = d.nmDictItem;
              obj.inpVal = d.inpVal; // 默认值
              elementArr.push(obj);
            });
          }
        });
      }
      const { matFileDictItem } = payload;

      elementArr.forEach((element, i) => {
        if (element.children && element.children.length) {
          element.children.forEach(item => {
            if (String(item.judgeLogicCode) === String(element.dftVal)) {
              elementArr.splice(i + 1, 0, item);
            }
          });
        }
      });

      return {
        ...state,
        coltFlag: payload.coltFlag,
        elementArr,
        matFileDictItem,
      };
    },
    matInfor(state, { payload }) {
      let { elementArr } = payload;
      const { element } = payload;
      if (String(element.inpType) === '4') {
        let index;
        /* eslint-disable no-unused-expressions */
        elementArr?.forEach((elem, i) => {
          if (String(elem.pageDetailId) === String(element.pageDetailId)) {
            index = i;
          }
        });
        if (element?.children?.length) {
          element.children.forEach(item => {
            if (String(item.judgeLogicCode) === String(element.inpVal)) {
              elementArr?.splice(index + 1, 0, item);
            } else {
              elementArr = elementArr?.filter(ele => ele.matId !== item.matId);
            }
          });
        }
      }

      return {
        ...state,
        elementArr,
      };
    },
    getEmpNameList(state, { payload }) {
      const empData = Array.isArray(payload) ? payload : [];
      return {
        ...state,
        empNameList: empData,
        empNameSelect: empData,
      };
    },
    fetchEmpName(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    getEmpNoList(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    // 清空
    clearEmpName(state, { payload }) {
      return {
        ...state,
        empNameSelect: payload,
      };
    },
    // 返回模版信息
    getTemplate(state, { payload }) {
      return {
        ...state,
        fileId: payload.split('|')[0],
        fileName: payload.split('|')[1],
      };
    },
    // 设置页签状态
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: {
                  payloadData: action.data,
                  tag: tagName,
                },
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
